package com.wind.trademark.file.dao.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import com.wind.trademark.base.vo.NodeVo;
import com.wind.trademark.common.dao.BaseDao;
import com.wind.trademark.common.vo.PageBean;
import com.wind.trademark.common.vo.PageParam;
import com.wind.trademark.file.dao.FileDao;
import com.wind.trademark.file.model.FiFile;
import com.wind.trademark.file.vo.FileVo;
@Repository
public class FileDaoImpl implements FileDao {

	@Autowired
	private BaseDao baseDao;
	@Override
	public PageBean queryFile(PageParam pageParam, Map<String, Object> params) {
		String sql= FileSql.queryFileSQL(params);
		PageBean pageBean=baseDao.queryPageBeanAndMapping(sql, pageParam,FileVo.class, params);
		return pageBean;
	}
	@Override
	public NodeVo getRootFileNode() {
		FiFile rootFile=this.baseDao.get(FiFile.class, 1L);
		NodeVo nodeVo=this.convert2NodeVo(new NodeVo(), rootFile);
		return nodeVo;
	}
	
	private NodeVo convert2NodeVo(NodeVo nodeVo,FiFile rootFile) {

		nodeVo.setId(rootFile.getId().toString());
		nodeVo.setText(rootFile.getName());
		nodeVo.setChecked(null);
		if(!rootFile.getChildren().isEmpty()&&rootFile.getType().equals("FILE")){
			for(FiFile doFile:rootFile.getChildren()){
				if(doFile.getType().equals("FILE")){
					NodeVo subNodeVo=convert2NodeVo(new NodeVo(),doFile);
					nodeVo.getChildren().add(subNodeVo);
				}

			}
		}
		//nodeVo.setLeaf(nodeVo.getChildren().isEmpty());
		return nodeVo;
	}
	@Override
	public List<FileVo> queryFileVoByFileId(Long fileId) {
		String sql= FileSql.queryFileVoByFileId();
		RowMapper<FileVo> rowMapper = ParameterizedBeanPropertyRowMapper.newInstance(FileVo.class);

		List<FileVo> result = baseDao.getNamedParameterJdbcTemplate().query(sql,new MapSqlParameterSource().addValue("fileId", fileId), rowMapper);

		return result;

	}
	@Override
	public void deleteFiles(List<Long> ids) {
		String sql= FileSql.deleteFiles();
		baseDao.getNamedParameterJdbcTemplate().update(sql,new MapSqlParameterSource().addValue("ids",ids));
	}

}
